package com.xzq.bugstack.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 18:53
 * @Version 1.0.0
 **/
@Data
public class NettyClient {

    private EventLoopGroup workerGroup = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture connect(String inetHost, int inetPort) {
        ChannelFuture channelFuture = null;
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new MyChannelInitializer());
            channelFuture = b.connect(inetHost, inetPort).sync();
            this.channel = channelFuture.channel();
        } catch (Exception e) {
                    e.printStackTrace();
        }finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                System.out.println("netty client start success");
            }else{
                System.out.println("netty client start error");
            }
        }
        return channelFuture;
    }
}
